<template>
  <c-loading :loading="loading">
    <view class="container">
      <view class="address-wrap block top-line" @tap="toSelectAddress">
        <c-icon size="40" icon="location" />
        <view class="address-box placeholder" v-if="!state.formData">请选择收货地址</view>
        <view class="address-box" v-else>
          <view class="consignee">
            <text class="name">{{ state.formData.consignee }}</text>
            <text>{{ state.formData.consigneePhone }}</text>
          </view>
          <view class="row2 address">{{ state.formData.region?.join(' ') }} {{ state.formData.address }}</view>
        </view>
        <c-icon icon="chevron-right" />
      </view>
      <view class="block">
        <template v-for="item in preOrder.items" :key="item.skuId">
          <order-item v-bind="item" />
        </template>
      </view>
      <view class="block box">
        <view class="row">
          <view class="label">合计</view>
          <view class="value"><c-number precision-mini :precision="2" class="price" prefix="￥" :value="preOrder.goodsAmount" /></view>
        </view>
        <view class="row">
          <view class="label">配送服务</view>
          <view class="value">
            <text class="marr">快递</text>
            <c-number precision-mini :precision="2" class="price" prefix="￥" v-if="preOrder.freightFee" :value="preOrder.freightFee" />
            <text v-else class="bold">包邮</text>
          </view>
        </view>
        <view class="row" @tap="toCoupon">
          <view class="label">优惠券</view>
          <view class="value flex al-center" v-if="canUseCouponRel.length">
            <text class="price" v-if="!preOrder.discountAmount">有{{ canUseCouponRel.length }}张可用</text>
            <c-number v-else precision-mini :precision="2" class="price" prefix="-￥" :value="preOrder.discountAmount" />
            <c-icon icon="chevron-right" />
          </view>
          <view class="value remark" v-else>
            <text>无可用</text>
            <c-icon icon="chevron-right" />
          </view>
        </view>
        <view class="row" v-if="preOrder.deductionAmount">
          <view class="label">会员减免</view>
          <view class="value"><c-number precision-mini :precision="2" class="price" prefix="-￥" :value="preOrder.deductionAmount" /></view>
        </view>
        <view class="row" @tap="(showRemark = true), (remarkInput = state.remark)">
          <view class="label">备注</view>
          <view class="value remark">
            {{ state.remark || '无备注' }}
            <c-icon color="var(--color-default)" icon="chevron-right" />
          </view>
        </view>
      </view>
      <view class="block"></view>
      <view class="fixed-footer flex al-center shadow">
        <c-number precision-mini :precision="2" class="price" prefix="￥" :value="preOrder.paymentAmount" />
        <view class="grow"></view>
        <c-button size="inline" class="round" type="danger" @tap="onOrder">立即支付</c-button>
      </view>
      <view class="end"></view>
    </view>
    <template #popup>
      <pay-complete v-model="showComplete" :success="paySuccess" @look="router.replace('/pagesOrder/order/info?id=' + state.orderNo)"></pay-complete>
      <c-popup v-model="showRemark">
        <view class="remark-wrap">
          <textarea class="textarea" maxlength="200" v-model="remarkInput" placeholder="无备注"></textarea>
          <view><c-button type="primary" @tap="(showRemark = false), (state.remark = remarkInput)">提交</c-button></view>
        </view>
      </c-popup>
    </template>
  </c-loading>
</template>
<script setup>
import { CButton, CLoading, CIcon, CNumber, CPopup } from '@/components';
import { useLoading, useRouter } from '@/hooks';
import { View, Text, Textarea } from '@tarojs/components';
import Taro from '@tarojs/taro';
import OrderItem from './components/order-item.vue';
import PayComplete from './components/pay-complete.vue';
import api from '@/api';
import { reactive, ref } from 'vue';
import { APPID } from '@/utils/config';

const showRemark = ref(false);
const router = useRouter();
const remarkInput = ref('');
const showComplete = ref(false);

const paySuccess = ref(true);
const state = reactive({
  fromCart: false,
  formData: null,
  discountId: null,
  items: [{ skuId: 123, qty: 1 }],
  remark: '',
  orderNo: ''
});
const canUseCouponRel = ref([]);
const preOrder = ref({});
const { loading } = useLoading(async (options, data) => {
  state.formData = await api.user.userAddressDefault();
  if (data) {
    state.items = data.items ?? [];
    state.fromCart = data.fromCart;
  }
  await loadOrder();
});

const toCoupon = () => {
  router.push('/pages/my/coupon', { select: true, selectId: state.discountId, canUse: canUseCouponRel.value }).then(data => {
    state.discountId = data;
    loadOrder();
  });
};
const loadOrder = async () => {
  const data = await api.order.preOrder({
    formData: state.formData,
    items: state.items,
    discountId: state.discountId
  });
  preOrder.value = data;
  if (data.canUseCouponRel) {
    canUseCouponRel.value = data.canUseCouponRel;
  }
};
const toSelectAddress = () => {
  router.push('/pages/my/address/index?select=1').then(address => {
    state.formData = address;
  });
};

const onOrder = async () => {
  if (!state.orderNo) {
    state.orderNo = await api.order.onOrder({
      formData: state.formData,
      fromCart: state.fromCart,
      items: state.items,
      discountId: state.discountId
    });
  }
  const packageV = await api.order.doPay({
    orderNo: state.orderNo,
    payChannel: 'WechatMini',
    partyAppId: APPID.value
  });
  Taro.requestPayment({
    ...packageV,
    success() {
      showComplete.value = true;
      paySuccess.value = true;
      // 支付成功
      api.order.queryPay({ orderNo: state.orderNo });
    },
    fail(e) {
      showComplete.value = true;
      paySuccess.value = false;
      // todo 支付失败
    }
  });
};
</script>
<style lang="scss">
.address-wrap {
  padding: 30px 30px 40px;
  display: flex;
  align-items: center;
  position: relative;
  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    height: 10px;
    width: 100%;
    background: var(--repeating-linear);
  }
  .address-box {
    margin-left: 20px;
    flex-grow: 1;
    .consignee {
      margin-bottom: 10px;
      color: var(--color-default);
      .name {
        font-weight: bold;
        margin-right: 10px;
      }
    }
    .address {
      font-size: 26px;
      line-height: 1.6em;
    }
  }
  .placeholder {
    font-size: 24px;
    color: var(--color-gray);
  }
}
.box {
  padding: 10px 30px;
  .row {
    display: flex;
    margin: 40px 0;
    justify-content: space-between;
    line-height: 1;
    font-size: 26px;
  }
  .price {
    color: var(--color-danger);
  }
  .remark {
    display: flex;
    color: var(--color-gray);
    align-items: center;
  }
  .marr {
    margin-right: 10px;
  }
}
.fixed-footer {
  .price {
    color: var(--color-danger);
    font-size: 36px;
    font-weight: bold;
  }
  .round {
    width: 220px;
  }
}
.remark-wrap {
  padding: 30px;
  padding-bottom: max(30px, var(--safe-bottom));
  .textarea {
    background-color: var(--color-background);
    height: 300px;
    margin: 10px 0 20px;
    width: 100%;
    box-sizing: border-box;
    padding: 20px;
    border-radius: 10px;
  }
}
</style>
